import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from "../Home";
import store from '@/store'
import {Message} from 'element-ui'


Vue.use(VueRouter)

const routes = [
  {
    path: '',
    name: 'Home',
    component: Home,
    children: [
      {
        path: '/',
        component: r => require.ensure([], () => r(require('@/views/Index')), 'index')
      },
      //所有分类
      {
        path: '/:type/all',
        component: r => require.ensure([], () => r(require('@/views/category/BlogAllCategoryTag')), 'blogallcategorytag')
      },

      //文章详情，需要在上面不然会被下面匹配
      {
        path: '/view/:id',
        component: r => require.ensure([], () => r(require('@/views/blog/BlogView')), 'blogview')
      },
      //精确分类
      {
        path: '/:type/:id',
        component: r => require.ensure([], () => r(require('@/views/blog/BlogCategoryTag')), 'blogcategorytag')
      },

    ],
  },
  {
    path: '/register',
    component: r => require.ensure([], () => r(require('@/views/Register')), 'register')
  },
  {
    path: '/login',
    component: r => require.ensure([], () => r(require('@/views/Login')), 'login')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})


router.beforeEach((to, from, next) => {

  if (store.state.token) {

    if (to.path === '/login') {
      next({path: '/'})
    } else {
      if (store.state.account.length === 0) {
        store.dispatch('getUserInfo').then(data => { //获取用户信息
          next()
        }).catch(() => {
          Message({
            type: 'warning',
            showClose: true,
            message: '登录已过期'
          })
          next({path: '/'})
        })
      } else {

        next()
      }
    }
  } else {
    if (to.matched.some(r => r.meta.requireLogin)) {
      Message({
        type: 'warning',
        showClose: true,
        message: '请先登录哦'
      })

    }
    else {
      next();
    }
  }
})

export default router
